//
//  MyTalkTableViewController.m
//  CoMeT
//
//  Created by Gang on 7/21/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "MyTalkTableViewController.h"
#import "DefaultTableViewCell.h"
#import "ColloquiumViewController.h"
#import "CoMeTAppDelegate.h"
#import "NetUtil.h"


@implementation MyTalkTableViewController

@synthesize talks;
@synthesize titleText;
@synthesize detailText;
@synthesize viewCount;
@synthesize bookmarkCount;
@synthesize activityIndicatorView;


-(void)synBookMark{
    CGRect frame = CGRectMake(0.0, 0.0, 25.0, 25.0);
    self.activityIndicatorView = [[UIActivityIndicatorView alloc]
                                  initWithFrame:frame];
    [self.activityIndicatorView sizeToFit];
    self.activityIndicatorView.autoresizingMask =
    (UIViewAutoresizingFlexibleLeftMargin |
     UIViewAutoresizingFlexibleRightMargin |
     UIViewAutoresizingFlexibleTopMargin |
     UIViewAutoresizingFlexibleBottomMargin);
    
    
    UIBarButtonItem *loadingView = [[UIBarButtonItem alloc] 
                                    initWithCustomView:self.activityIndicatorView];
    [self.activityIndicatorView startAnimating];
    
    self.navigationItem.rightBarButtonItem = loadingView;
    [loadingView release];
    
    
    
    if ([NetUtil checkNetworkStatus:nil] ==0) {
        UIAlertView *networkfail = [[UIAlertView alloc] initWithTitle:@"Error" message:@"No Wifi or WWAN Connection!"
                                                             delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [networkfail show];
        [networkfail release]; 
        
        return;
    }
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    
    NSString *hostStr =[NSString stringWithFormat:@"http://halley.exp.sis.pitt.edu/", [prefs valueForKey:@"userid"]];
    
    NSURL *url=[[NSURL alloc] initWithString:hostStr];
    
    NSMutableURLRequest *urlRequest=[NSMutableURLRequest requestWithURL:url];
    [url release];
    
    [urlRequest setHTTPMethod:@"POST"];
    [urlRequest setHTTPBody:[hostStr dataUsingEncoding:NSASCIIStringEncoding]];
    [urlRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    
    
    NSURLResponse *response;
    NSError *error;
    NSData *aData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
    NSString *serverOutputSch = [[NSString alloc] initWithData:aData encoding: NSASCIIStringEncoding];
    
    //NSLog(@"%@", serverOutputSch);
    
    NSMutableArray *tmpList =[[NSMutableArray alloc] init];
    
    TBXML * tbxml = [[TBXML alloc] initWithXMLString:serverOutputSch];
    
    TBXMLElement * root = tbxml.rootXMLElement;
    
    // if root element is valid
    if (root) {
        
        // search for the Items element within the root element's children
        TBXMLElement *Items = [TBXML childElementNamed:@"Items" parentElement:root];
        Content *tempContent = nil;
        NSString *contentIDText = nil;
        while (Items != nil) {
            // search the Items' child elements for an Item element
            TBXMLElement *Item = [TBXML childElementNamed:@"Item" parentElement:Items];
            
            while (Item != nil)
            {
                // search the Item's child elements for a paperID element
                
                
                TBXMLElement *tempElment= [TBXML childElementNamed:@"contentID" parentElement:Item];
                contentIDText = [TBXML textForElement:tempElment];
                //NSLog(@"%@", contentIDText);
                tempContent = [Content ContentWithId:contentIDText inManagedObjectContext:self.managedObjectContext];
                
                if (tempContent != nil) {
                    [tmpList addObject:tempContent];
                }
                
                Item = [TBXML nextSiblingNamed:@"Item" searchFromElement:Item];
            }
            
            Items = [TBXML nextSiblingNamed:@"Items" searchFromElement:Items];
        }
    }
    
    [serverOutputSch release];
    [tbxml release];   
    
    
    NSSortDescriptor *nameSortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)] autorelease] ;
    
    
    
    NSArray * descriptors =
    [NSArray arrayWithObjects:nameSortDescriptor, nil];
    NSArray * sortedArray =
    [tmpList sortedArrayUsingDescriptors:descriptors];
    
    [tmpList release];
    
    self.recommendations = [[NSMutableArray alloc] initWithArray:sortedArray];
    [self.activityIndicatorView stopAnimating];
    [self.tableView reloadData];
    
} 

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    if (self.talks == nil) {
        self.talks = [[NSMutableArray alloc] init];
    }	
    

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
}




- (void)viewDidUnload
{
    talks= nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    CoMeTAppDelegate* appDelegate = [[UIApplication sharedApplication] delegate];;
    self.talks =   [appDelegate bookmarks];
    [self.tableView reloadData];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    // Return the number of rows in the section.
    return  [talks count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    return  100.0f;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    static NSString *CellIdentifier = @"DefaultTalbeViewCell";
    
    DefaultTableViewCell *cell = (DefaultTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"DefaultTableViewCell" owner:nil options:nil];
        
        for(id currentObject in topLevelObjects)
        {
            if([currentObject isKindOfClass:[DefaultTableViewCell class]])
            {
                cell = (DefaultTableViewCell *)currentObject;
                break;
            }
        }
        
    }
    

    
    // Set up the cell...  
    
    
    cell.titleText.text = [[self.talks objectAtIndex:indexPath.row]  objectForKey:@"title"];
    cell.author.text = [[self.talks objectAtIndex:indexPath.row] objectForKey:@"detail"];
    
    
    cell.viewCount.text = [[self.talks objectAtIndex:indexPath.row] objectForKey:@"viewCount"];
    
    if ( [cell.viewCount.text isEqualToString:@"0"]) {
        [cell.eyeIcon setHidden:YES];
    }
    
    cell.bookmarkCount.text = [[self.talks objectAtIndex:indexPath.row]  objectForKey:@"bookmarkCount"];
    
    if ([cell.bookmarkCount.text isEqualToString:@"0"]) {
        [cell.starIcon setHidden:YES];
    }
    return cell;
    
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ColloquiumViewController *colloquiumView = [[ColloquiumViewController alloc]init];
    
    colloquiumView.talk = [self.talks objectAtIndex:indexPath.row];
    
    [self.navigationController pushViewController:colloquiumView animated:YES];
    
    [colloquiumView release];
}

@end
